package com.example.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Log;
import com.example.entity.Users;
import com.example.repository.UsersMapper;
import com.example.service.LogService;
import com.example.service.UsersService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 切面处理
 * */
@Component
@Aspect
public class LogAspect {

    @Resource
    private LogService logService;

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Around("@annotation(autoLog)")
    public Object doAround(ProceedingJoinPoint joinPoint,AutoLog autoLog) throws Throwable{

        //操作内容
        String logName = autoLog.value();
        //操作时间(当前时间)
        String logTime = DateUtil.now();
        //操作人
        String userName = "";
        Users user = JwtTokenUtils.getCurrentUser();
        if(ObjectUtil.isNotNull(user)){
            userName = user.getUserName();
        }
        //操作人ip
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();

        //用户登录
        Result result = (Result) joinPoint.proceed();

        //登陆后，记录登录日志
        Object data = result.getData();
        if(data instanceof Users){
            Users loginUser = (Users) data;
            userName = loginUser.getUserName();
        }
        //封装Log实体
        Log log = new Log(null,logName,logTime,userName,ip);
        logService.addLog(log);

        return result;
    }
}
